// 所有用户数据管理
import { defineStore } from "pinia"
import { loginAPI } from '@/apis/user.js'
import { ref } from 'vue'
import { useCartStore } from './cartstore'
import { mergeCartAPI } from '@/apis/cart.js'
export const getUse = defineStore('user', () => {
  const usecartStore = useCartStore()
  // 1.定义数据state
  const getUseStore = ref({})
  // 2.方法
  const useStore = async ({ account, password }) => {
    const res = await loginAPI({ account, password })
    getUseStore.value = res.result
    // 合并购物车
    await mergeCartAPI(usecartStore.cartList.map(item => {
      return {
        skuId: item.skuId,
        selected: item.selected,
        count: item.count
      }
    }))
    usecartStore.getNewCart()
  }
  // 清除token
  const clearUseStore = () => {
    getUseStore.value = {}
    usecartStore.clearCartList()
  }
  // 3.将数据和方法return
  return {
    getUseStore,
    useStore,
    clearUseStore
  }
}, {
  persist: true
})
